package com.aizuda.boot.modules.business.contractName.service.impl;

import com.aizuda.boot.modules.business.contract.dto.UserInfo;
import com.aizuda.boot.modules.business.contract.util.AuthUtil;
import com.aizuda.boot.modules.business.contractName.domain.entity.ContractNameRule;
import com.aizuda.boot.modules.business.contractName.domain.entity.ContractNameRuleComponent;
import com.aizuda.boot.modules.common.constant.enums.Component;
import com.aizuda.boot.modules.common.constant.enums.DepartmentRule;
import com.aizuda.boot.modules.common.constant.enums.MultipleEntityRule;
import com.aizuda.boot.modules.business.contractName.domain.request.GenerateNameDTO;
import com.aizuda.boot.modules.business.contractName.domain.request.NameComponent;
import com.aizuda.boot.modules.business.contractName.domain.request.NameRuleSaveDTO;
import com.aizuda.boot.modules.business.contractName.domain.response.ContractNameRuleDetailVO;
import com.aizuda.boot.modules.business.contractName.domain.response.ContractNameRuleListVO;
import com.aizuda.boot.modules.business.contractName.domain.response.NameComponentVO;
import com.aizuda.boot.modules.business.contractName.mapper.ContractNameRuleMapper;
import com.aizuda.boot.modules.business.contractName.service.ContractNameRuleComponentService;
import com.aizuda.boot.modules.business.contractName.service.ContractNameRuleService;
import com.aizuda.boot.modules.business.counterparty.entity.CounterpartyInfoEntity;
import com.aizuda.boot.modules.business.counterparty.entity.LegalEntityDetailEntity;
import com.aizuda.boot.modules.business.counterparty.mapper.CounterpartyInfoMapper;
import com.aizuda.boot.modules.business.counterparty.mapper.LegalEntityDetailMapper;
import com.aizuda.boot.modules.business.performance.mapper.ContractTypeMapper;
import com.aizuda.boot.modules.system.entity.SysDepartment;
import com.aizuda.boot.modules.system.mapper.SysDepartmentMapper;
import com.aizuda.core.api.ApiAssert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author sangyirong
 * @ClassName ContractNameRuleServiceImpl
 * @Version 1.0
 * @Date 2025/7/4 16:14
 */
@Service
public class ContractNameRuleServiceImpl extends ServiceImpl<ContractNameRuleMapper, ContractNameRule> implements ContractNameRuleService {

    @Resource
    private ContractNameRuleComponentService contractNameRuleComponentService;

    @Resource
    private ContractTypeMapper contractTypeMapper;

    @Resource
    private SysDepartmentMapper sysDepartmentMapper;

    @Resource
    private LegalEntityDetailMapper legalEntityDetailMapper;

    @Resource
    private CounterpartyInfoMapper counterpartyInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(NameRuleSaveDTO dto) {
        // 获取当前用户信息
        UserInfo currentUser = AuthUtil.getCurrentUser();
        ApiAssert.fail(Objects.isNull(currentUser.getEmployeeId()), "当前用户未登录，不允许创建!");

        // 参数校验
        ApiAssert.fail(Objects.isNull(dto), "合同名称规则数据不能为空");
        ApiAssert.fail(!StringUtils.hasText(dto.getRuleName()), "规则名称不能为空");
        ApiAssert.fail(!StringUtils.hasText(dto.getRuleCode()), "规则编码不能为空");
        ApiAssert.fail(Objects.isNull(dto.getRuleType()), "规则类型不能为空");

        // 检查规则名称是否重复
        long nameCount = this.count(new LambdaQueryWrapper<ContractNameRule>()
                .eq(ContractNameRule::getRuleName, dto.getRuleName()));
        ApiAssert.fail(nameCount > 0, "规则名称已存在");

        // 检查规则编码是否重复
        long codeCount = this.count(new LambdaQueryWrapper<ContractNameRule>()
                .eq(ContractNameRule::getRuleCode, dto.getRuleCode()));
        ApiAssert.fail(codeCount > 0, "规则编码已存在");

        // 创建合同名称规则主表数据
        ContractNameRule ruleEntity = new ContractNameRule();
        BeanUtils.copyProperties(dto, ruleEntity);
        if (Objects.isNull(dto.getIsEnabled())) {
            ruleEntity.setIsEnabled(true); // 默认启用
        }

        // 保存主表数据
        boolean saveResult = this.save(ruleEntity);
        ApiAssert.fail(!saveResult, "保存合同名称规则失败");

        // 保存规则组件数据
        if (!CollectionUtils.isEmpty(dto.getComponents())) {
            List<ContractNameRuleComponent> componentEntities = new ArrayList<>();
            int sortOrder = 1; // 排序值从1开始自动生成
            for (NameComponent component : dto.getComponents()) {
                if (Objects.isNull(component.getComponentType())) {
                    continue; // 跳过组件类型为空的数据
                }

                ContractNameRuleComponent componentEntity = new ContractNameRuleComponent();
                componentEntity.setRuleId(ruleEntity.getId());
                componentEntity.setComponentType(component.getComponentType());
                componentEntity.setComponentValue(component.getComponentValue());
                componentEntity.setSortOrder(sortOrder++); // 自动生成排序值

                componentEntities.add(componentEntity);
            }

            if (!componentEntities.isEmpty()) {
                boolean componentSaveResult = contractNameRuleComponentService.saveBatch(componentEntities);
                ApiAssert.fail(!componentSaveResult, "保存合同名称规则组件失败");
            }
        }

        return true;
    }

    @Override
    public List<ContractNameRuleListVO> getList() {
        // 查询所有合同名称规则
        List<ContractNameRule> ruleEntities = this.list(new LambdaQueryWrapper<ContractNameRule>()
                .orderByAsc(ContractNameRule::getCreateTime));

        if (CollectionUtils.isEmpty(ruleEntities)) {
            return new ArrayList<>();
        }

        List<ContractNameRuleListVO> result = new ArrayList<>();

        for (ContractNameRule ruleEntity : ruleEntities) {
            ContractNameRuleListVO vo = new ContractNameRuleListVO();
            vo.setId(ruleEntity.getId());
            vo.setRuleName(ruleEntity.getRuleName());
            vo.setRuleCode(ruleEntity.getRuleCode());
            vo.setRuleType(ruleEntity.getRuleType());
            vo.setEdit(ruleEntity.getEdit());
            vo.setOurEntityRule(ruleEntity.getOurEntityRule());
            vo.setCounterpartyEntityRule(ruleEntity.getCounterpartyEntityRule());

            // 查询规则对应的组件
            List<ContractNameRuleComponent> componentEntities = contractNameRuleComponentService.list(
                    new LambdaQueryWrapper<ContractNameRuleComponent>()
                            .eq(ContractNameRuleComponent::getRuleId, ruleEntity.getId())
                            .orderByAsc(ContractNameRuleComponent::getSortOrder));

            if (!CollectionUtils.isEmpty(componentEntities)) {
                List<NameComponentVO> componentVOs = new ArrayList<>();
                for (ContractNameRuleComponent componentEntity : componentEntities) {
                    NameComponentVO componentVO = new NameComponentVO();
                    componentVO.setId(componentEntity.getId());
                    componentVO.setComponentType(componentEntity.getComponentType());
                    componentVO.setComponentValue(componentEntity.getComponentValue());
                    componentVO.setSortOrder(componentEntity.getSortOrder());

                    componentVOs.add(componentVO);
                }
                vo.setComponents(componentVOs);
            } else {
                vo.setComponents(new ArrayList<>());
            }

            result.add(vo);
        }

        return result;
    }

    @Override
    public ContractNameRuleDetailVO getDetail(Long ruleId) {
        ContractNameRule rule = this.getById(ruleId);
        if (null == rule) {
            ApiAssert.fail("合同名称规则不存在");
        }

        ContractNameRuleDetailVO vo = new ContractNameRuleDetailVO();
        vo.setId(rule.getId());
        vo.setRuleName(rule.getRuleName());
        vo.setRuleCode(rule.getRuleCode());
        vo.setEdit(rule.getEdit());
        vo.setRuleType(rule.getRuleType());
        vo.setIsEnabled(rule.getIsEnabled());
        vo.setOurEntityRule(rule.getOurEntityRule());
        vo.setCounterpartyEntityRule(rule.getCounterpartyEntityRule());

        List<NameComponentVO> components = contractNameRuleComponentService.list(Wrappers.<ContractNameRuleComponent>lambdaQuery()
                        .eq(ContractNameRuleComponent::getRuleId, ruleId)
                        .orderByAsc(ContractNameRuleComponent::getSortOrder))
                .stream().map(item -> {
                    NameComponentVO componentVO = new NameComponentVO();
                    componentVO.setComponentType(item.getComponentType());
                    componentVO.setComponentValue(item.getComponentValue());
                    componentVO.setSortOrder(item.getSortOrder());
                    return componentVO;
                }).collect(Collectors.toList());
        vo.setComponents(components);

        List<Component> enums = Component.getComponentsByRuleType(rule.getRuleType());
        List<Map<String, Object>> maps = new ArrayList<>();
        enums.forEach(item -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("code", item.getCode());
            map.put("msg", item.getMsg());
            if (null != item.getValues()) {
                map.put("values", item.getValues());
            }
            maps.add(map);
        });
        vo.setComponent(maps);

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRule(NameRuleSaveDTO dto) {
        // 获取当前用户信息
        UserInfo currentUser = AuthUtil.getCurrentUser();
        ApiAssert.fail(Objects.isNull(currentUser.getEmployeeId()), "当前用户未登录，不允许修改!");

        // 参数校验
        ApiAssert.fail(Objects.isNull(dto), "合同名称规则数据不能为空");
        ApiAssert.fail(Objects.isNull(dto.getId()), "规则ID不能为空");
        ApiAssert.fail(!StringUtils.hasText(dto.getRuleName()), "规则名称不能为空");
        ApiAssert.fail(!StringUtils.hasText(dto.getRuleCode()), "规则编码不能为空");
        ApiAssert.fail(Objects.isNull(dto.getRuleType()), "规则类型不能为空");

        // 检查规则是否存在
        ContractNameRule existingRule = this.getById(dto.getId());
        ApiAssert.fail(Objects.isNull(existingRule), "合同名称规则不存在");

        // 检查规则名称是否重复（排除当前记录）
        long nameCount = this.count(new LambdaQueryWrapper<ContractNameRule>()
                .eq(ContractNameRule::getRuleName, dto.getRuleName())
                .ne(ContractNameRule::getId, dto.getId()));
        ApiAssert.fail(nameCount > 0, "规则名称已存在");

        // 检查规则编码是否重复（排除当前记录）
        long codeCount = this.count(new LambdaQueryWrapper<ContractNameRule>()
                .eq(ContractNameRule::getRuleCode, dto.getRuleCode())
                .ne(ContractNameRule::getId, dto.getId()));
        ApiAssert.fail(codeCount > 0, "规则编码已存在");

        // 更新合同名称规则主表数据
        ContractNameRule ruleEntity = new ContractNameRule();
        BeanUtils.copyProperties(dto, ruleEntity);
        if (Objects.isNull(dto.getIsEnabled())) {
            ruleEntity.setIsEnabled(existingRule.getIsEnabled()); // 保持原有启用状态
        }

        // 更新主表数据
        boolean updateResult = this.updateById(ruleEntity);
        ApiAssert.fail(!updateResult, "更新合同名称规则失败");

        // 删除原有的规则组件数据
        boolean deleteResult = contractNameRuleComponentService.remove(
                new LambdaQueryWrapper<ContractNameRuleComponent>()
                        .eq(ContractNameRuleComponent::getRuleId, dto.getId()));

        // 保存新的规则组件数据
        if (!CollectionUtils.isEmpty(dto.getComponents())) {
            List<ContractNameRuleComponent> componentEntities = new ArrayList<>();
            int sortOrder = 1; // 排序值从1开始自动生成
            for (NameComponent component : dto.getComponents()) {
                if (Objects.isNull(component.getComponentType())) {
                    continue; // 跳过组件类型为空的数据
                }

                ContractNameRuleComponent componentEntity = new ContractNameRuleComponent();
                componentEntity.setRuleId(dto.getId());
                componentEntity.setComponentType(component.getComponentType());
                componentEntity.setComponentValue(component.getComponentValue());
                componentEntity.setSortOrder(sortOrder++); // 自动生成排序值

                componentEntities.add(componentEntity);
            }

            if (!componentEntities.isEmpty()) {
                boolean componentSaveResult = contractNameRuleComponentService.saveBatch(componentEntities);
                ApiAssert.fail(!componentSaveResult, "保存合同名称规则组件失败");
            }
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeRule(Long ruleId) {
        // 获取当前用户信息
        UserInfo currentUser = AuthUtil.getCurrentUser();
        ApiAssert.fail(Objects.isNull(currentUser.getEmployeeId()), "当前用户未登录，不允许删除!");

        // 参数校验
        ApiAssert.fail(Objects.isNull(ruleId), "规则ID不能为空");

        // 检查规则是否存在
        ContractNameRule existingRule = this.getById(ruleId);
        ApiAssert.fail(Objects.isNull(existingRule), "合同名称规则不存在");

        // 先删除规则组件数据
        boolean deleteComponentResult = contractNameRuleComponentService.remove(
                new LambdaQueryWrapper<ContractNameRuleComponent>()
                        .eq(ContractNameRuleComponent::getRuleId, ruleId));

        // 删除主表数据
        boolean deleteRuleResult = this.removeById(ruleId);
        ApiAssert.fail(!deleteRuleResult, "删除合同名称规则失败");

        return true;
    }

    @Override
    public String getContractName(GenerateNameDTO dto) {
        // 获取当前用户信息
        UserInfo currentUser = AuthUtil.getCurrentUser();
        ApiAssert.fail(Objects.isNull(currentUser.getEmployeeId()), "当前用户未登录，不允许生成合同名称!");

        // 参数校验
        ApiAssert.fail(Objects.isNull(dto), "生成合同名称参数不能为空");
        ApiAssert.fail(Objects.isNull(dto.getRuleType()), "合同名称规则ID不能为空");

        // 获取合同名称规则
        ContractNameRule rule = this.getOne(Wrappers.<ContractNameRule>lambdaQuery()
                .eq(ContractNameRule::getRuleType, dto.getRuleType())
                .last("limit 1"));
        ApiAssert.fail(Objects.isNull(rule), "合同名称规则不存在");
        ApiAssert.fail(!rule.getIsEnabled(), "合同名称规则未启用");

        // 获取规则组件列表，按排序顺序排列
        List<ContractNameRuleComponent> components = contractNameRuleComponentService.list(new LambdaQueryWrapper<ContractNameRuleComponent>()
                .eq(ContractNameRuleComponent::getRuleId, rule.getId())
                .orderByAsc(ContractNameRuleComponent::getSortOrder));

        // 如果没有组件，返回原合同名称
        if (CollectionUtils.isEmpty(components)) {
            return StringUtils.hasText(dto.getFileName()) ? dto.getFileName() : "未定义合同名称";
        }

        // 用于跟踪是否已经处理过我方主体和对方主体
        boolean ourPartyProcessed = false;
        boolean counterpartyProcessed = false;

        // 生成合同名称
        StringBuilder contractNameBuilder = new StringBuilder();
        for (ContractNameRuleComponent component : components) {
            try {
                String componentValue = generateComponentValue(component, dto, rule, ourPartyProcessed, counterpartyProcessed);
                if (StringUtils.hasText(componentValue)) {
                    contractNameBuilder.append(componentValue);
                    
                    // 更新处理状态
                    Component componentType = component.getComponentType();
                    if (componentType == Component.OUR_PARTY_FULL_NAME || componentType == Component.OUR_PARTY_SHORT_NAME) {
                        ourPartyProcessed = true;
                    } else if (componentType == Component.COUNTERPARTY_FULL_NAME || componentType == Component.COUNTERPARTY_SHORT_NAME) {
                        counterpartyProcessed = true;
                    }
                }
            } catch (Exception e) {
                // 如果某个组件生成失败，记录错误但继续处理其他组件
                System.err.println("生成组件值失败: " + component.getComponentType() + ", 错误: " + e.getMessage());
                // 可以考虑添加默认值或跳过该组件
                contractNameBuilder.append("[组件错误]");
            }
        }

        String generatedName = contractNameBuilder.toString();

        // 如果生成的名称为空，返回原合同名称或默认值
        if (!StringUtils.hasText(generatedName)) {
            return StringUtils.hasText(dto.getContractName()) ? dto.getContractName() : "未定义合同名称";
        }

        return generatedName;
    }

    /**
     * 生成组件值
     *
     * @param component 组件
     * @param dto       生成参数
     * @param rule      合同名称规则
     * @param ourPartyProcessed 是否已经处理过我方主体
     * @param counterpartyProcessed 是否已经处理过对方主体
     * @return 组件值
     */
    private String generateComponentValue(ContractNameRuleComponent component, GenerateNameDTO dto, ContractNameRule rule, boolean ourPartyProcessed, boolean counterpartyProcessed) {
        Component componentType = component.getComponentType();
        String componentValue = component.getComponentValue();

        switch (componentType) {
            case FREE_TEXT:
                // 自由文本直接返回组件值
                return componentValue;

            case CONNECTOR:
                // 连接符直接返回组件值
                return componentValue;

            case DATE:
                // 日期根据格式返回当前日期
                return formatDate(componentValue);

            case MAIN_CONTRACT_FILE_NAME:
            case SUPPLEMENT_AGREEMENT_FILE_NAME:
            case TERMINATE_AGREEMENT_FILE_NAME:
                return null == dto.getFileName() ? "undefined" : dto.getFileName();

            case SUPPLEMENT_AGREEMENT_TITLE:
            case TERMINATE_AGREEMENT_TITLE:
            case MAIN_CONTRACT_TITLE:
                return null == dto.getFileTitle() ? "undefined" : dto.getFileTitle();

            case ORIGINAL_CONTRACT_NAME:
                // 合同相关信息返回原合同名称
                return dto.getContractName();

            case CONTRACT_TYPE_ABBREVIATION:
                // 合同类型返回缩写名称
                return null == dto.getContractTypeId() ? "default" : contractTypeMapper.selectById(dto.getContractTypeId()).getTypeAbbreviation();
            case INCOME_EXPENSE_TYPE_FULL_NAME:
                return null == dto.getDocumentType() ? "undefined" : dto.getDocumentType();
            case CONTRACT_HANDLER_DEPARTMENT:
                return getDepartmentName(DepartmentRule.valueOf(componentValue), dto.getDepartmentId());
            case OUR_PARTY_FULL_NAME:
                // 我方全称
                // 如果规则是只第一次添加且已经处理过我方主体，则跳过
                if (rule.getOurEntityRule() == MultipleEntityRule.FIRST_ONLY && ourPartyProcessed) {
                    return "";
                }
                return getOurPartyName(dto.getLegalId(), true, rule.getOurEntityRule());
            case OUR_PARTY_SHORT_NAME:
                // 我方简称
                // 如果规则是只第一次添加且已经处理过我方主体，则跳过
                if (rule.getOurEntityRule() == MultipleEntityRule.FIRST_ONLY && ourPartyProcessed) {
                    return "";
                }
                return getOurPartyName(dto.getLegalId(), false, rule.getOurEntityRule());
            case COUNTERPARTY_FULL_NAME:
                // 对方全称
                // 如果规则是只第一次添加且已经处理过对方主体，则跳过
                if (rule.getCounterpartyEntityRule() == MultipleEntityRule.FIRST_ONLY && counterpartyProcessed) {
                    return "";
                }
                return getCounterpartyName(dto.getCounterpartyId(), true, rule.getCounterpartyEntityRule());
            case COUNTERPARTY_SHORT_NAME:
                // 对方简称
                // 如果规则是只第一次添加且已经处理过对方主体，则跳过
                if (rule.getCounterpartyEntityRule() == MultipleEntityRule.FIRST_ONLY && counterpartyProcessed) {
                    return "";
                }
                return getCounterpartyName(dto.getCounterpartyId(), false, rule.getCounterpartyEntityRule());
            case CONTRACT_FIELD:
                // 这些字段需要根据实际业务逻辑获取，这里返回默认值
                return getField();

            default:
                return "";
        }
    }

    private String getDepartmentName(DepartmentRule rule, Long departmentId) {
        // 参数校验
        if (rule == null || departmentId == null) {
            return "undefined";
        }

        try {
            // 获取部门的完整路径（从顶级到当前部门）
            List<SysDepartment> departmentPath = sysDepartmentMapper.selectDepartmentPath(departmentId);

            if (CollectionUtils.isEmpty(departmentPath)) {
                return "undefined";
            }

            // departmentPath是按层级从高到低排序的，第一个是顶级部门，最后一个是当前部门
            // 当前经办人部门就是路径中的最后一个部门
            SysDepartment currentDepartment = departmentPath.get(departmentPath.size() - 1);

            switch (rule) {
                case CURRENT_HANDLER_DEPT:
                    // 当前经办人部门
                    return currentDepartment.getName();

                case TOP_LEVEL_DEPT:
                    // 最高级经办人部门（顶级部门）
                    return departmentPath.get(0).getName();

                case TOP_LEVEL_SUB_1:
                case TOP_LEVEL_SUB_2:
                case TOP_LEVEL_SUB_3:
                case TOP_LEVEL_SUB_4:
                case TOP_LEVEL_SUB_5:
                case TOP_LEVEL_SUB_6:
                case TOP_LEVEL_SUB_7:
                case TOP_LEVEL_SUB_8:
                case TOP_LEVEL_SUB_9:
                    // 最高级经办人部门下N级
                    int targetLevel = getTargetLevel(rule);

                    // 如果要求的层级超过了实际部门层级，使用经办人部门
                    if (targetLevel >= departmentPath.size()) {
                        return currentDepartment.getName();
                    }

                    // 返回指定层级的部门名称
                    return departmentPath.get(targetLevel).getName();

                default:
                    return currentDepartment.getName();
            }
        } catch (Exception e) {
            // 异常处理，返回默认值
            return "undefined";
        }
    }

    /**
     * 根据部门规则获取目标层级
     *
     * @param rule 部门规则
     * @return 目标层级（0表示顶级部门，1表示下一级，以此类推）
     */
    private int getTargetLevel(DepartmentRule rule) {
        switch (rule) {
            case TOP_LEVEL_SUB_1:
                return 1;
            case TOP_LEVEL_SUB_2:
                return 2;
            case TOP_LEVEL_SUB_3:
                return 3;
            case TOP_LEVEL_SUB_4:
                return 4;
            case TOP_LEVEL_SUB_5:
                return 5;
            case TOP_LEVEL_SUB_6:
                return 6;
            case TOP_LEVEL_SUB_7:
                return 7;
            case TOP_LEVEL_SUB_8:
                return 8;
            case TOP_LEVEL_SUB_9:
                return 9;
            default:
                return 0;
        }
    }

    /**
     * 格式化日期
     *
     * @param dateFormat 日期格式
     * @return 格式化后的日期字符串
     */
    private String formatDate(String dateFormat) {
        if (!StringUtils.hasText(dateFormat)) {
            dateFormat = "yyyyMMdd"; // 默认格式
        }

        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
            return LocalDateTime.now().format(formatter);
        } catch (Exception e) {
            // 如果格式错误，返回默认格式的日期
            return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        }
    }

    /**
     * 获取我方主体名称
     *
     * @param legalId 我方实体ID
     * @param isFullName 是否返回全称，true返回全称，false返回简称
     * @param entityRule 多个我方主体时生成规则
     * @return 我方主体名称
     */
    private String getOurPartyName(Integer legalId, boolean isFullName, MultipleEntityRule entityRule) {
        // 参数校验
        if (legalId == null) {
            return "undefined";
        }

        try {
            // 目前只处理单个主体的情况，多主体逻辑预留
            // 如果需要支持多个主体，可以根据entityRule来决定是否显示所有主体或只显示第一个
            LegalEntityDetailEntity legalEntity = legalEntityDetailMapper.selectById(legalId);
            if (legalEntity == null) {
                return "undefined";
            }

            if (isFullName) {
                return legalEntity.getLegalEntityName() != null ? legalEntity.getLegalEntityName() : "undefined";
            } else {
                return legalEntity.getLegalEntityAbbr() != null ? legalEntity.getLegalEntityAbbr() : "undefined";
            }
        } catch (Exception e) {
            // 异常处理，返回默认值
            return "undefined";
        }
    }

    /**
     * 获取对方主体名称
     *
     * @param counterpartyId 对方实体ID
     * @param isFullName 是否返回全称，true返回全称，false返回简称
     * @param entityRule 多个对方主体时生成规则
     * @return 对方主体名称
     */
    private String getCounterpartyName(Integer counterpartyId, boolean isFullName, MultipleEntityRule entityRule) {
        // 参数校验
        if (counterpartyId == null) {
            return "undefined";
        }

        try {
            // 目前只处理单个主体的情况，多主体逻辑预留
            // 如果需要支持多个主体，可以根据entityRule来决定是否显示所有主体或只显示第一个
            CounterpartyInfoEntity counterparty = counterpartyInfoMapper.selectById(counterpartyId);
            if (counterparty == null) {
                return "undefined";
            }

            // 注意：目前交易方实体没有简称字段，全称和简称都使用全称
            return counterparty.getCounterpartyName() != null ? counterparty.getCounterpartyName() : "undefined";
        } catch (Exception e) {
            // 异常处理，返回默认值
            return "undefined";
        }
    }

    private String getField() {
        return "field";
    }
}
